﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IWshRuntimeLibrary;
using System.Net;
using System.IO;

namespace IEWrapper
{
    public partial class AddNew : Form
    {
        public AddNew()
        {
            InitializeComponent();
        }

        private void AddNew_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Escape)
                Application.Exit();
        }

        private void AddNew_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (chkDesktop.Checked)
                    CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), this.textBox1.Text);
                if (chkQuckLunch.Checked)
                    CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Interent", this.textBox1.Text);
                if (chkStart.Checked)
                    CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), this.textBox1.Text);

                //C:\Users\Ales\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch
                MainForm mf = new MainForm(this.textBox1.Text);
                mf.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot create shortcut. Please try again.","Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                
            }
        }

        private void CreateShortcut(string path, string args)
        {
            //char[] notChar = {'\\','/',':','*','?','"','<','>','|'};

            //TODO narest threading

            //if (args.Contains("facebook"))
            //    args = args.Replace("www.", "");

            //WebRequest request = HttpWebRequest.Create(args);
            //WebResponse response = request.GetResponse();
            //System.IO.Stream stream = response.GetResponseStream();
            //HtmlParser.HtmlDocument document = HtmlParser.HtmlDocument.Create(stream);
            //stream.Close();
            //response.Close();

            WshShellClass wsh = new WshShellClass();
            IWshRuntimeLibrary.IWshShortcut shortcut;
            //shortcut = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(path + "\\" + GetTitle(document.Nodes).Replace('\\', ' ').Replace('\n', ' ').Replace('/', ' ').Replace(':', '-').Replace('*', ' ').Replace('?', ' ').Replace('"', ' ').Replace('<', ' ').Replace('>', ' ').Replace('|', ' ').Trim() + ".lnk");
            shortcut = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(path + "\\" + args.Replace("http://", "").Replace("https://", "").Replace("www.", "").Replace("/", "").Trim() + ".lnk");
            shortcut.Arguments = args;
            shortcut.TargetPath = Application.ExecutablePath;
            //shortcut.Description = GetMetaDescription(document.Nodes).Substring(0, 255) + " ...";
            if (!Directory.Exists(Application.StartupPath + "\\icons"))
                Directory.CreateDirectory(Application.StartupPath + "\\icons");
            string[] files = Directory.GetFiles(Application.StartupPath + "\\icons");

            foreach (string file in files)
            {
                if (args.Contains(file.Replace(Application.StartupPath + "\\icons\\","").Replace(".ico", "")))
                    shortcut.IconLocation = file;
            }
            

            shortcut.Save();
        }

        private void AddNew_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawLine(new Pen(Color.Silver), 190, 54, this.Width - 20, 54);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        //KODA ZA PARSAT HTML - BO TREBA KAKO DRGAC NARDIT, KER TOLE JE BUGASTO
        //static string GetTitle(HtmlParser.HtmlNodeCollection nodes)
        //{
        //    string ret = "";
            
        //    foreach (HtmlParser.HtmlNode node in nodes)
        //    {
        //        HtmlParser.HtmlElement element = node as HtmlParser.HtmlElement;
        //        if (null != element)
        //        {
        //            if ((element.Name.ToLower() == "title"))
        //            {
        //                ret = element.Text.Replace("\n","");
        //                break;
        //            }
        //            else
        //                ret = GetTitle((node as HtmlParser.HtmlElement).Nodes);

        //            if (ret != "")
        //                break;
        //        }

        //    }
        //    return ret;
        //}

        //static string GetMetaDescription(HtmlParser.HtmlNodeCollection nodes)
        //{
        //    string ret = "";
        //    foreach (HtmlParser.HtmlNode node in nodes)
        //    {
        //        HtmlParser.HtmlElement element = node as HtmlParser.HtmlElement;
        //        if (null != element)
        //        {
        //            if ((element.Name.ToLower() == "meta") && (element.Attributes["name"] != null))
        //            {
        //                if (element.Attributes["name"].Value.ToLower() == "description")
        //                {
        //                    ret = element.Attributes["content"].Value;
        //                    break;
        //                }
        //            }
        //            else
        //                ret = GetMetaDescription((node as HtmlParser.HtmlElement).Nodes);

        //            if (ret != "")
        //                break;
        //        }
        //    }
        //    return ret;
        //}

    }
}
